package com.cstz.ydshop.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.common.collect.Maps;

public class HttpClientUtils {

    private static final Logger LOGGER = Logger.getLogger(HttpClientUtils.class);
    private static ClientConnectionManager connectionManager = null;
    private static HttpParams httpParams = null;

    static {
        httpParams = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(httpParams, 100);
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(50));
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 300000);
        SchemeRegistry schreg = new SchemeRegistry();
        schreg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schreg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        connectionManager = new ThreadSafeClientConnManager(httpParams, schreg);
    }

    /**
     * Reset connection timeout and socket timeout for new http connections.
     *
     * @param timeout the timeout value in millisecond.
     */
    public static void setTimeout(int timeout) {
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }

    /**
     * Return a new httpClient using default configuration parameters.
     *
     * @return A new HttpClient object.
     */
    public static HttpClient getHttpClient() {
        return new DefaultHttpClient(connectionManager, httpParams);
    }

    public static String getResponseByGet(final String url, int time) {
        HttpClient httpClient = getHttpClient();
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, time);
        return getResponseByGet(httpClient, url);
    }

    /**
     * Send a http 'get' request to given url and return the response content.
     *
     * @param url the url that the request will be sent to.
     * @return the response content got from the specified url.
     */
    public static String getResponseByGet(String url) {
        return getResponseByGet(new DefaultHttpClient(connectionManager, httpParams), url);
    }

    /**
     * Send a http 'get' request to given url via the given httpClient object,
     * and return the response content.
     *
     * @param httpClient the apache httpClient object that manages the request.
     * @param url the url that the request will be sent to.
     * @return the response content got from the specified url.
     */
    private static String getResponseByGet(HttpClient httpClient, String url) {
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String output = "";
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (null != entity) {
                    output = EntityUtils.toString(entity);
                }
            }
            if (null != entity) {
                entity.consumeContent();
            }
            return output;
        } catch (ClientProtocolException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
            throw new RuntimeException("Get URL content HTTP error", e);
        } catch (IOException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
            throw new RuntimeException("Get URL content IO error", e);
        } finally {
            //httpClient.getConnectionManager().shutdown();
        }
    }

    public static byte[] getResponseBytesByGet(String url) {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            httpClient = new DefaultHttpClient(connectionManager, httpParams);
            httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            byte[] output = null;
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (null != entity) {
                    output = EntityUtils.toByteArray(entity);
                }
            }
            if (null != entity) {
                entity.consumeContent();
            }
            return output;
        } catch (ClientProtocolException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
        } catch (IOException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
        } finally {
            //httpClient.getConnectionManager().shutdown();
        }
        return null;
    }

    /**
     * Send a http 'post' request to given url and return the response content.
     *
     * @param url the url that the request will be sent to.
     * @param paramsMap the parameters will be sent to given url.
     * @return the response content got from the specified url.
     */
    public static String getResponseByPost(String url, Map<String, String> paramsMap) {
        if (null == paramsMap || paramsMap.size() == 0) {
            return getResponseByGet(getHttpClient(), url);
        } else {
            return getResponseByPost(getHttpClient(), url, paramsMap, null, null);
        }
    }

    /**
     * get response by post method
     *
     * @param httpClient
     * @param url
     * @param paramsMap
     * @return
     */
    private static String getResponseByPost(HttpClient httpClient, String url, Map<String, String> paramsMap,
            String requestXML, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost(url);
        try {
        	//httpPost.addHeader("Content-Type","application/json;charset=utf-8");    
        	
            //add params
            if (null != paramsMap && paramsMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (String name : paramsMap.keySet()) {
                	LOGGER.info("请求参数,name:"+name+",value:"+paramsMap.get(name));
                    nvps.add(new BasicNameValuePair(name, paramsMap.get(name)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            } else {
                StringEntity reqEntity = new StringEntity(requestXML);
                httpPost.setEntity(reqEntity);
            }

            //add http header
            if (null != headerMap && headerMap.size() > 0) {
                List<Header> headers = new ArrayList<Header>();
                for (String name : headerMap.keySet()) {
                    Header header = new BasicHeader(name, headerMap.get(name));
                    headers.add(header);
                }
                httpPost.setHeaders(headers.toArray(headers.toArray(new Header[headers.size()])));
            }

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String output = "";
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (null != entity) {
                    output = EntityUtils.toString(entity);
                }
            }
            if (null != entity) {
                // call the HttpEntity#consumeContent() method to consume any available content on the stream. HttpClient
                // will automatically release the underlying connection back to the connection manager as soon as it
                // detects that the end of the content stream has been reached.
                entity.consumeContent();
            }
            return output;
        } catch (Exception e) {
            httpPost.abort();
            LOGGER.error("Fialed to get response!", e);
            return null;
        }
    }
    
   public static String getResponseByPostBody(String url, 
            String requestXML, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost(url);
        try {
        	//httpPost.addHeader("Content-Type","application/json;charset=utf-8");    
        	
        	StringEntity reqEntity = new StringEntity(requestXML);
            httpPost.setEntity(reqEntity);

            //add http header
            if (null != headerMap && headerMap.size() > 0) {
                List<Header> headers = new ArrayList<Header>();
                for (String name : headerMap.keySet()) {
                    Header header = new BasicHeader(name, headerMap.get(name));
                    headers.add(header);
                }
                httpPost.setHeaders(headers.toArray(headers.toArray(new Header[headers.size()])));
            }

            HttpClient httpClient = getHttpClient();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String output = "";
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (null != entity) {
                    output = EntityUtils.toString(entity);
                }
            }
            if (null != entity) {
                // call the HttpEntity#consumeContent() method to consume any available content on the stream. HttpClient
                // will automatically release the underlying connection back to the connection manager as soon as it
                // detects that the end of the content stream has been reached.
                entity.consumeContent();
            }
            return output;
        } catch (Exception e) {
            httpPost.abort();
            LOGGER.error("Fialed to get response!", e);
            return null;
        }
    }
   
   public static String getResponseByGetBody(String url, 
            Map<String, String> headerMap) {
       HttpGet httpPost = new HttpGet(url);
       try {
       	//httpPost.addHeader("Content-Type","application/json;charset=utf-8");    
       	
       	
           //add http header
           if (null != headerMap && headerMap.size() > 0) {
               List<Header> headers = new ArrayList<Header>();
               for (String name : headerMap.keySet()) {
                   Header header = new BasicHeader(name, headerMap.get(name));
                   headers.add(header);
               }
               httpPost.setHeaders(headers.toArray(headers.toArray(new Header[headers.size()])));
           }

           HttpClient httpClient = getHttpClient();
           HttpResponse response = httpClient.execute(httpPost);
           HttpEntity entity = response.getEntity();
           String output = "";
           if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
               if (null != entity) {
                   output = EntityUtils.toString(entity);
               }
           }
           if (null != entity) {
               // call the HttpEntity#consumeContent() method to consume any available content on the stream. HttpClient
               // will automatically release the underlying connection back to the connection manager as soon as it
               // detects that the end of the content stream has been reached.
               entity.consumeContent();
           }
           return output;
       } catch (Exception e) {
           httpPost.abort();
           LOGGER.error("Fialed to get response!", e);
           return null;
       }
   }

    /**
     * Get https request result
     *
     * @param httpsUrl
     * @return
     */
    public static byte[] getHttpsResult(String httpsUrl) {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();
            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            httpClient = new DefaultHttpClient(mgr, client.getParams());
            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            httpGet = new HttpGet(httpsUrl);
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            byte[] output = null;
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                if (null != entity) {
                    output = EntityUtils.toByteArray(entity);
                }
            }
            if (null != entity) {
                // call the HttpEntity#consumeContent() method to consume any available content on the stream. HttpClient
                // will automatically release the underlying connection back to the connection manager as soon as it
                // detects that the end of the content stream has been reached.
                entity.consumeContent();
            }
            return output;
        } catch (ClientProtocolException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
        } catch (IOException e) {
            if (httpGet != null) {
                httpGet.abort();
            }
        } finally {
            //httpClient.getConnectionManager().shutdown();
        }
        return null;
    }
    
    public static void main(String[] args) {
    	String jsonStr="111";
		Map<String,String> headMap = Maps.newHashMap();
		headMap.put("duuuid", "fd22b670c9350cd5");
		headMap.put("duimei", "866693025816963");
		headMap.put("duplatform", "android");
		headMap.put("duchannel", "huawei");
		headMap.put("duv", "4.3.0");
		headMap.put("dulogintoken", "b844e17b|46879866|32f1f52d36fd1809");
		headMap.put("dudevicetrait", "HUAWEI+GRA-TL00");
		headMap.put("timestamp", System.currentTimeMillis()+"");
		headMap.put("shumeiid", "20190626130715a772bb2b6e4c82ef6807484712a87f23016692497d458c69");
		headMap.put("user-agent", "duapp/4.3.0(android;6.0)");
		headMap.put("user-agent", "duapp/4.3.0(android;6.0)");
		headMap.put("cookie", "duToken=d41d8cd9%7C46879866%7C1561525663%7Cc013cf5db834187f");
		headMap.put("accept-encoding", "gzip");
		headMap.put("ygjh8wsq", "Bi1uXXajiXUnDeHQISeGVNHh5eUA6VnMbyZDpMmi3xdoFrXIWgR-LVehcXE51uaAfu5Y72XRgNRizzTfLBWGrNd0hJGptyGgdsEE5n9mVTdmm9VK0z2VFmEmnhX9X9U-eaj9bAELEmOJneG3srKb-GLq7S6_c4W5OouFuWIQXI5OUetEMZp_F0KA1i9Q9d58y7LWMfYYvNjnPGGWJ7zxHAFJcUbFYdlR3fVqhFUa5z0lngaziuNJUx0UoE6LILlKwB4zJ8zFRt69107MYcIYf-tUYPSbCpaxqFcv16d0T4lWZOWVi4bfV9Zb3w-xOvf6ub6NLjtVZh_O81_1qpuImdFhPDo..DpjdVa1oFyFnn7-ZcoeCFI7KHi2Gp6a5Lr6CwI2ZS5jf1-H4lAJwTmWE98YrAsMHvVTSKyZF1EsCDHj3iIy9gArNLa11i61oFW-EXv_pOjN0zOuR692NhGyd6mtomZHv5aOoDySTEweIqUnfQ8AezSYIHrI0U8qKYjbjzjxdSrw7Wp85SpBv_eblLo3rYm8guIswnJGTfYQuDWOy6t4JUEZGqQogHf7puO5_t-i59IGCwcZgyifcu1OiX2nSbGBXC2oDczLX6yaVrYancaMoCC791yQCeshmokTDpkX85cETze21DzYBe3REQfjjElReq_qqNj1kErNcpPa7RO9L1xur3pt3uinnuWvE8Ck-P7JgHIC95PkjJFH-PhCGEOlSsoC48MYwp2rloLUWx3hKyDm-0YAAlVR9l6-ETj7CWzbqZA1oIvikZx3zd9A1ZtN7Zsie91RCneUKMa5NqHWSXWNJKV1ZtbiWyaGd5BhyJw-3pIbiA0Csm7Arr6gqOHhY2JMcbF2OTLBTQ-RQT_nEJGJ2R32Ise7lWQFBTSbKfOirEKCXW2KKMgqcyT0qL6JBBgfvtgVaheY48LYmAo-mVhxHhKdbbsRg1Wkk6d74gbHF1qmyOPzaa9ZpcLO1q1sWgcc4wtLS2TbTosGT1VZgOV-idW2tccucau_6pF0Bj58y5lnJgHCNvEF9m9-NVxV3UVsBe2PzS6SB577UfUT88w3N98964K");
		
		headMap = Maps.newHashMap();
		headMap.put("duuuid", "fd22b670c9350cd5");
		headMap.put("duimei", "866693025816963");
		headMap.put("duplatform", "android");
		headMap.put("duchannel", "huawei");
			
		//headMap = Maps.newHashMap();
		
		//String responseStr = HttpClientUtils.getResponseByGetBody("https://m.poizon.com/menu/shopping?lastId=&limit=20&signNo=&tabId=0&newSign=84125d43d8918a7436bdbe31b64c8ac7",headMap);
		//String responseStr = HttpClientUtils.getResponseByPostBody("http://localhost:8016/bdc/apiuser/login?apiUser=fcj&apiPassword=111111","",headMap);
		
		Map<String,String> paramsMap = Maps.newHashMap();
		paramsMap.put("xml", "<操作*>正式挂失</操作*><用户名*>419900</用户名*><密码*>AAAAAbbbbb</密码*><社会保障卡卡号*>X12400597</社会保障卡卡号*><社会保障号码*>41052619910613003X</社会保障号码*><姓名*>小张</姓名*><开户银行></开户银行><银行卡号></银行卡号>");
		paramsMap.put("sbbh", "866693025816963");
		
		HttpClient httpClient = getHttpClient();
		String responseStr = HttpClientUtils.getResponseByPost(httpClient, "http://localhost/card/wsdl//allDsjk", paramsMap, null, headMap);
		System.out.println("responseStr:"+responseStr);
		
		
	}
}
